<?php
// +-------------------------------------------------------------------------------
// | DingZone [ A Rapid Development Framework For Dingtalk ]
// +-------------------------------------------------------------------------------
// | TableInfoHelper.php v1.0
// |
// | Copyright (c) 2014-2018 http://www.heimalanshi.com All rights reserved.
// | Author : Jie
// | Date : 2018-09-16
// +-------------------------------------------------------------------------------


namespace app\extend\db;


use think\Config;
use think\Db;

class TableInfoHelper {

    /**
     * 获取数据表字段信息
     *
     * @param $tableName
     * @param array $dbConfig
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public static function getColumns($tableName, $dbConfig = []) {
        $dbConfig = self::_mergeDbConfig($dbConfig);
        $tableName = $dbConfig['prefix'] . $tableName;
        return Db::connect($dbConfig)->query("SHOW FULL COLUMNS FROM `" . $tableName . "`");
    }

    /**
     * 获取数据库中的所有表
     *
     * @param bool $pattern
     * @param array $dbConfig
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public static function getTables($pattern = false, $dbConfig = []) {
        $dbConfig = self::_mergeDbConfig($dbConfig);
        $prefix = $dbConfig['prefix'];
        $prefixLength = strlen($prefix);
        $sql = "SHOW TABLES" . ($pattern ? " LIKE '" . $prefix . $pattern . "%'" : "") . ";";
        $tableInfos = Db::connect($dbConfig)->query($sql);
        $tables = [];
        foreach ($tableInfos as $tableInfo) {
            $tableName = array_values($tableInfo)[0];
            $tableName = substr($tableName, $prefixLength);
            $tables[] = $tableName;
        }
        return $tables;
    }

    /**
     * 判断列类型是否为数字
     *
     * @param $type
     * @return bool
     */
    public static function isColumnTypeNumeric($type) {
        if (startsWith($type, "int(")) {
            return true;
        }
        if (startsWith($type, "tinyint(")) {
            return true;
        }
        if (startsWith($type, "smallint(")) {
            return true;
        }
        if (startsWith($type, "mediumint(")) {
            return true;
        }
        if (startsWith($type, "bigint(")) {
            return true;
        }
        if ($type == "double") {
            return true;
        }
        return false;
    }

    /**
     * @param $dbConfig
     * @return array
     */
    private static function _mergeDbConfig($dbConfig) {
        $dbConfig = array_merge(Config::get("database"), $dbConfig);
        return $dbConfig;
    }
}